﻿using Microsoft.AspNetCore.Http;
using Repository.Impl;
using Utils.Helper;
using SqlSugar;
using System.Security.Claims;
using Model;

namespace Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public ISqlSugarClient db => GetDbClient();

        public UnitOfWork(ISqlSugarClient sqlSugarClient, IHttpContextAccessor httpContextAccessor)
        {
            _sqlSugarClient = sqlSugarClient;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取DB，保证唯一性
        /// </summary>
        /// <returns></returns>
        public SqlSugarScope GetDbClient()
        {
            // 必须要as，后边会用到切换数据库操作
            return _sqlSugarClient as SqlSugarScope;
        }

        public void BeginTran()
        {
            GetDbClient().BeginTran();
        }

        public void CommitTran()
        {
            try
            {
                GetDbClient().CommitTran();
            }
            catch (Exception ex)
            {
                GetDbClient().RollbackTran();
                throw ex;
            }
        }

        public void RollbackTran()
        {
            GetDbClient().RollbackTran();
        }

        public List<IConditionalModel> GetQueryParam(List<QueryParam> obj)
        {
            var str = ConvertHelper.ObjToJson(obj);
            if (!string.IsNullOrEmpty(str))
            {
                var conModels = _sqlSugarClient.Utilities.JsonToConditionalModels(str);
                return conModels;
            }
            else
            {
                return new List<IConditionalModel>();
            }
        }

    }

}
